/**
 *
 */
package org.suren.littlebird.server;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import org.apache.cxf.aegis.databinding.AegisDatabinding;
import org.apache.cxf.frontend.ClientProxyFactoryBean;
import org.eclipse.jface.preference.IPreferenceStore;
import org.suren.littlebird.Activator;
import org.suren.littlebird.preferences.PreferenceConstants;

/**
 * @author suren
 *
 */
public class BundleServerFactory
{
	private static BundleServer server;
	private static ClientProxyFactoryBean factory;
	private static String url;
	private static final IPreferenceStore store = Activator.getDefault().getPreferenceStore();

	public static BundleServer getInstance()
	{
		url = store.getString(PreferenceConstants.P_OSGI_SERVER);
		if(url == null || server == null || factory == null || !factory.getAddress().equals(url))
		{
			factory = getClientProxy();
			server = (BundleServer) factory.create();
		}
		else
		{
			factory = null;
			server = null;
		}

		return server;
	}

	private static ClientProxyFactoryBean getClientProxy()
	{
		int port =store.getInt(PreferenceConstants.P_OSGI_PORT);

		String host = url + ":" + port + "/bundle";
		if(!host.startsWith("http://") && !host.startsWith("https://"))
		{
			host = "http://" + host;
		}

		return getClientProxy(host, BundleServer.class);
	}

	private static ClientProxyFactoryBean getClientProxy(String url, Class<BundleServer> clazz)
	{
		ClientProxyFactoryBean factory = new ClientProxyFactoryBean();

		factory.setAddress(url);
		factory.setServiceClass(BundleServer.class);
		factory.getServiceFactory().setDataBinding(new AegisDatabinding());

		return factory;
	}

	public static void main(String[] args)
	{
		getBundleServer();
	}

	public static void getBundleServer()
	{
		try
		{
			Registry reg = LocateRegistry.getRegistry("10.0.32.4", 8989);
			Remote serverObj = reg.lookup("rmi://10.0.32.4:8989/org.suren.littlebird.server.DefaultBundleServer");

			System.out.println(serverObj);
		}
		catch (RemoteException e)
		{
			e.printStackTrace();
		}
		catch (NotBoundException e)
		{
			e.printStackTrace();
		}
	}
}
